package com.example.myactiviti.common.util;

import com.example.myactiviti.common.exception.BizException;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.util.concurrent.TimeUnit;
import java.util.function.Function;

/**
 * 锁执行器
 */

@Component
public class LockInvker  implements ApplicationContextAware{

    private static RedisTemplate<String,Object> redisTemplate;



    public static <R,T> R invoker(Function<T,R> function, T req,String lockKey){
        try {
            Boolean acquired  = redisTemplate.opsForValue().setIfAbsent(lockKey, "TRUE", 5, TimeUnit.MINUTES);
            if (acquired) {
                return function.apply(req);
            }
        }catch (Exception e){
            throw new BizException("任务执行失败",e);
        }finally {
            redisTemplate.delete(lockKey);
        }
        throw new BizException("未获取到redis锁");
    }


    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        redisTemplate = applicationContext.getBean(RedisTemplate.class);
    }
}
